package com.sntk.commongetway;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.sntk.commongetway.autho.AuthoService;
import com.sntk.commongetway.resp.ResponseData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.util.ObjectUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.function.Consumer;

/**
 * @ClassName: AuthoFilter
 * @author: wgchao
 * @createTime: 2020/11/23 8:56 AM
 * @Description: 身份认证
 */
public class AuthoFilter implements GlobalFilter, Ordered {

    @Autowired
    private AuthoService authoService;

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("身份认证-----------");
        String url = exchange.getRequest().getURI().toString();
        if(url.contains("/passtoken")){//无需认证的接口
            Consumer<HttpHeaders> httpHeaders = httpHeader -> {
                httpHeader.set("from", "gateway");
            };
            ServerHttpRequest serverHttpRequest = exchange.getRequest().mutate().headers(httpHeaders).build();
            exchange.mutate().request(serverHttpRequest).build();
            return chain.filter(exchange);
        }else{
            String token = exchange.getRequest().getHeaders().getFirst("accessToken");
            if (ObjectUtils.isEmpty(token)) {
                System.out.println("token缺失");
                exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
                return exchange.getResponse().setComplete();
            }else {
                //身份认证
                ResponseData obj = authoService.autho(token);
                if(obj.getCode().equals("200")){
                    Consumer<HttpHeaders> httpHeaders = httpHeader -> {
                        httpHeader.set("logininfo", JSON.toJSONString(obj.getData()));
                        httpHeader.set("from", "gateway");
                    };
                    ServerHttpRequest serverHttpRequest = exchange.getRequest().mutate().headers(httpHeaders).build();
                    exchange.mutate().request(serverHttpRequest).build();
                }else {
                    System.out.println("身份认证失败");
                    exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
                    return exchange.getResponse().setComplete();
                }
            }
            return chain.filter(exchange);
        }
    }


}
